<template>
  <div class="workingci-page">
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="90">
        <el-form-item label="班次名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入班次名称"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="班次颜色">
          <el-select
            v-model="searchForm.color"
            placeholder="请选择颜色"
            clearable
            style="width: 200px"
            :loading="colorOptionsLoading"
          >
            <el-option
              v-for="item in colorOptions"
              :key="item"
              :label="item"
              :value="item"
            >
              <div class="color-option">
                <span class="color-dot" :style="{ background: item }" />
                <span>{{ item }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-toolbar">
        <el-button type="success" @click="openCreateDialog">新增班次</el-button>
        <el-button
          type="danger"
          :disabled="!selectedIds.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="workingname" label="班次名称" min-width="140" />
        <el-table-column prop="workingjname" label="班次简称" min-width="120" />
        <el-table-column label="班次颜色" min-width="140">
          <template #default="{ row }">
            <div class="color-cell">
              <span class="color-dot" :style="{ background: row.workingcolor }" />
              <span>{{ row.workingcolor }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" min-width="160">
          <template #default="{ row }">
            {{ formatDatetime(row.createtimes) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" min-width="160">
          <template #default="{ row }">
            {{ formatDatetime(row.endtimes) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="desc"
          label="备注"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEditDialog(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="560px"
      destroy-on-close
      draggable
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-width="110"
      >
        <el-form-item label="班次名称" prop="workingname">
          <el-input v-model="dialogForm.workingname" placeholder="请输入班次名称" />
        </el-form-item>
        <el-form-item label="班次简称" prop="workingjname">
          <el-input v-model="dialogForm.workingjname" placeholder="请输入班次简称" />
        </el-form-item>
        <el-form-item label="班次颜色" prop="workingcolor">
          <div class="color-picker">
            <el-input
              v-model="dialogForm.workingcolor"
              placeholder="#409EFF"
              style="width: 180px"
            />
            <el-color-picker v-model="dialogForm.workingcolor" show-alpha />
          </div>
        </el-form-item>
        <el-form-item label="开始时间" prop="createtimes">
          <el-date-picker
            v-model="dialogForm.createtimes"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endtimes">
          <el-date-picker
            v-model="dialogForm.endtimes"
            type="datetime"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="dialogForm.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="handleSubmit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import https from '@/Http/http'
import dayjs from 'dayjs'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from 'element-plus'

interface Workingci {
  id: number
  workingname: string
  workingjname: string
  workingcolor: string
  createtimes: string
  endtimes: string
  desc: string
}


const loading = ref(false)
const saving = ref(false)
const tableData = ref<Workingci[]>([])
const multipleSelection = ref<Workingci[]>([])
const colorOptions = ref<string[]>([])
const colorOptionsLoading = ref(false)

const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0
})

const searchForm = reactive({
  name: '',
  color: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('新增班次')
const dialogMode = ref<'create' | 'edit'>('create')
const dialogFormRef = ref<FormInstance>()
const dialogForm = reactive({
  id: 0,
  workingname: '',
  workingjname: '',
  workingcolor: '#409EFF',
  createtimes: '',
  endtimes: '',
  desc: ''
})

const dialogRules: FormRules = {
  workingname: [{ required: true, message: '请输入班次名称', trigger: 'blur' }],
  workingjname: [{ required: true, message: '请输入班次简称', trigger: 'blur' }],
  workingcolor: [{ required: true, message: '请选择班次颜色', trigger: 'change' }],
  createtimes: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endtimes: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

const selectedIds = computed(() => multipleSelection.value.map(item => item.id))

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T = any>(payload: any): T =>
  (payload?.data ?? payload?.Data) as T
const getPayloadMsg = (payload: any): string =>
  payload?.msg ?? payload?.Msg ?? ''
const getTotalCount = (payload: any) =>
  payload?.totalCount ?? payload?.TotalCount ?? 0

const formatDatetime = (val?: string | Date) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD HH:mm')
}

const fetchWorkingcis = async () => {
  loading.value = true
  try {
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      name: searchForm.name || undefined,
      color: searchForm.color || undefined
    }
    const { data } = await https.Reads.get("/Working/ShowWorkingci", { params })
    if (getStatusCode(data) === 1) {
      tableData.value = getPayloadData<Workingci[]>(data) ?? []
      pagination.totalCount = getTotalCount(data)
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取班次失败')
    }
  } catch (error: any) {
    console.error('fetchWorkingcis error', error)
    ElMessage.error(error?.message || '获取班次失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchColorOptions = async () => {
  colorOptionsLoading.value = true
  try {
    const { data } = await https.Reads.get("/Working/ShowWorkingci", {
      params: { pageindex: 1, pagesize: 1000 }
    })
    if (getStatusCode(data) === 1) {
      const colors = getPayloadData<Workingci[]>(data)?.map(item => item.workingcolor) ?? []
      colorOptions.value = Array.from(new Set(colors.filter(Boolean)))
    }
  } catch (error) {
    console.error('fetchColorOptions error', error)
  } finally {
    colorOptionsLoading.value = false
  }
}

const handleSearch = () => {
  pagination.pageindex = 1
  fetchWorkingcis()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.color = ''
  pagination.pageindex = 1
  fetchWorkingcis()
}

const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchWorkingcis()
}

const handlePageChange = (val: number) => {
  pagination.pageindex = val
  fetchWorkingcis()
}

const handleSelectionChange = (rows: Workingci[]) => {
  multipleSelection.value = rows
}

const resetDialogForm = () => {
  dialogForm.id = 0
  dialogForm.workingname = ''
  dialogForm.workingjname = ''
  dialogForm.workingcolor = '#409EFF'
  dialogForm.createtimes = ''
  dialogForm.endtimes = ''
  dialogForm.desc = ''
  dialogFormRef.value?.clearValidate()
}

const openCreateDialog = () => {
  dialogMode.value = 'create'
  dialogTitle.value = '新增班次'
  resetDialogForm()
  dialogVisible.value = true
}

const openEditDialog = (row: Workingci) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑班次'
  dialogForm.id = row.id
  dialogForm.workingname = row.workingname
  dialogForm.workingjname = row.workingjname
  dialogForm.workingcolor = row.workingcolor
  dialogForm.createtimes = row.createtimes
  dialogForm.endtimes = row.endtimes
  dialogForm.desc = row.desc || ''
  dialogVisible.value = true
  dialogFormRef.value?.clearValidate()
}

const submitAdd = async () => {
  const payload = {
    workingname: dialogForm.workingname,
    workingjname: dialogForm.workingjname,
    workingcolor: dialogForm.workingcolor,
    createtimes: dialogForm.createtimes,
    endtimes: dialogForm.endtimes,
    desc: dialogForm.desc
  }
  const { data } = await https.Writes.post("/Workingci/AddWorkingci", payload)
  return data
}

const submitUpdate = async () => {
  const payload = {
    id: dialogForm.id,
    workingname: dialogForm.workingname,
    workingjname: dialogForm.workingjname,
    workingcolor: dialogForm.workingcolor,
    createtimes: dialogForm.createtimes,
    endtimes: dialogForm.endtimes,
    desc: dialogForm.desc
  }
  const { data } = await https.Writes.put("/Workingci/UpdateWorkingci", payload)
  return data
}

const handleSubmit = () => {
  dialogFormRef.value?.validate(async valid => {
    if (!valid) return
    saving.value = true
    try {
      const result =
        dialogMode.value === 'create' ? await submitAdd() : await submitUpdate()
      if (getStatusCode(result) === 1) {
        ElMessage.success(getPayloadMsg(result) || '操作成功')
        dialogVisible.value = false
        fetchWorkingcis()
        fetchColorOptions()
      } else {
        ElMessage.error(getPayloadMsg(result) || '操作失败')
      }
    } catch (error: any) {
      console.error('handleSubmit error', error)
      ElMessage.error(error?.message || '保存失败，请稍后重试')
    } finally {
      saving.value = false
    }
  })
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择需要删除的班次')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedIds.value.length} 条班次数据吗？`,
      '提示',
      { type: 'warning' }
    )
    const { data } = await https.Writes.delete("/Workingci/DelAllWorkingci", {
      data: { ids: selectedIds.value }
    })
    if (getStatusCode(data) === 1) {
      ElMessage.success(getPayloadMsg(data) || '删除成功')
      fetchWorkingcis()
      fetchColorOptions()
    } else {
      ElMessage.error(getPayloadMsg(data) || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error', error)
      ElMessage.error(error?.message || '删除失败，请稍后重试')
    }
  }
}

onMounted(() => {
  fetchWorkingcis()
  fetchColorOptions()
})
</script>

<style scoped>
.workingci-page {
  padding: 16px;
  background: #f5f7fa;
}

.filter-card {
  margin-bottom: 12px;
}

.table-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.color-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.color-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  display: inline-block;
}

.color-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-picker {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style>


